
package org.springxrsk.modules.classes.controller;

import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import lombok.AllArgsConstructor;
import jakarta.validation.Valid;

import org.apache.commons.beanutils.BeanUtils;
import org.springxrsk.core.secure.XrskUser;
import org.springxrsk.core.secure.annotation.PreAuth;
import org.springxrsk.core.mp.support.Condition;
import org.springxrsk.core.mp.support.Query;
import org.springxrsk.core.tool.api.R;
import org.springxrsk.core.tool.utils.Func;
import org.springxrsk.modules.classes.pojo.entity.QyClassesLessonsDetailsEntity;
import org.springxrsk.modules.classes.service.IQyClassesLessonsDetailsService;
import org.springxrsk.modules.system.service.IUserService;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springxrsk.modules.classes.pojo.entity.QyClassesLessonsEntity;
import org.springxrsk.modules.classes.pojo.vo.QyClassesLessonsVO;
import org.springxrsk.modules.classes.excel.QyClassesLessonsExcel;
import org.springxrsk.modules.classes.wrapper.QyClassesLessonsWrapper;
import org.springxrsk.modules.classes.service.IQyClassesLessonsService;
import org.springxrsk.core.boot.ctrl.XrskController;
import org.springxrsk.core.tool.utils.DateUtil;
import org.springxrsk.core.excel.util.ExcelUtil;
import org.springxrsk.core.tool.constant.XrskConstant;
import org.springxrsk.core.tool.constant.RoleConstant;

import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.DayOfWeek;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

import jakarta.servlet.http.HttpServletResponse;

//import static org.springxrsk.common.utils.CommonUtil.BetweenDays;
import static org.springxrsk.common.utils.CommonUtil.getDays;
import static org.springxrsk.common.utils.CommonUtil.getWeekDays;

/**
 * 课表 控制器
 *
 *  @author
 * @since 2024-06-23
 */
@RestController
@AllArgsConstructor
@RequestMapping("xrsk-qyClasses/qyClassesLessons")
@Tag(name = "课表", description = "课表接口")
public class QyClassesLessonsController extends XrskController {

	private final IUserService userService;
	private final IQyClassesLessonsService qyClassesLessonsService;
	private final IQyClassesLessonsDetailsService qyClassesLessonsDetailsService;

	/**
	 * 课表 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@Operation(summary = "详情", description  = "传入qyClassesLessons")
	public R<QyClassesLessonsVO> detail(QyClassesLessonsEntity qyClassesLessons) {
		QyClassesLessonsEntity detail = qyClassesLessonsService.getOne(Condition.getQueryWrapper(qyClassesLessons));
		return R.data(QyClassesLessonsWrapper.build().entityVO(detail));
	}
	/**
	 * 课表 分页
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@Operation(summary = "分页", description  = "传入qyClassesLessons")
	public R<IPage<QyClassesLessonsVO>> list(QyClassesLessonsVO qyClassesLessons, Query query) {
		IPage<QyClassesLessonsVO> pages = qyClassesLessonsService.selectQyClassesLessonsPage(Condition.getPage(query), qyClassesLessons);
		pages.getRecords().forEach(item->{
			List<String> names = new ArrayList<>();
			Arrays.stream(item.getTeacherIds().split(",")).forEach(subitem->{
				names.add( userService.getById(subitem).getName());
			});
			item.setTeacherNames(names.stream().collect(Collectors.joining(",")));
		});
		return R.data(pages);
	}

//	public R<IPage<QyClassesLessonsVO>> list(@Parameter(hidden = true) @RequestParam Map<String, Object> qyClassesLessons, Query query) {
//		IPage<QyClassesLessonsEntity> pages = qyClassesLessonsService.page(Condition.getPage(query), Condition.getQueryWrapper(qyClassesLessons, QyClassesLessonsEntity.class));
//		return R.data(QyClassesLessonsWrapper.build().pageVO(pages));
//	}

	/**
	 * 课表 自定义分页
	 */
	@GetMapping("/page")
	@ApiOperationSupport(order = 3)
	@Operation(summary = "分页", description  = "传入qyClassesLessons")
	public R<IPage<QyClassesLessonsVO>> page(QyClassesLessonsVO qyClassesLessons, Query query) {
		IPage<QyClassesLessonsVO> pages = qyClassesLessonsService.selectQyClassesLessonsPage(Condition.getPage(query), qyClassesLessons);
		return R.data(pages);
	}

	/**
	 * 课表 新增
	 */
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@Operation(summary = "新增", description  = "传入qyClassesLessons")
	public R save(@Valid @RequestBody QyClassesLessonsEntity qyClassesLessons) {

		boolean tage = qyClassesLessonsService.save(qyClassesLessons);
		Map<String, Object> map = new HashMap<>();
		map.put("lessons_id", qyClassesLessons.getId());
		if(tage){
			switch (Integer.valueOf( qyClassesLessons.getRepetitive())){
				case 0://不重复
				{
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					List<String> days = getDays(qyClassesLessons.getStartTime(), qyClassesLessons.getStartTime());
					qyClassesLessonsDetailsService.realReamove(map);
					AtomicReference<Integer> idx = new AtomicReference<>(1);
					days.forEach(item->{
						String begin = item+" "+qyClassesLessons.getSubStartTime()+":00";
						String end	 = item+" "+qyClassesLessons.getSubEndTime()+":00";

						QyClassesLessonsDetailsEntity one = new QyClassesLessonsDetailsEntity();

						try {
							BeanUtils.copyProperties(one,qyClassesLessons);
							one.setLessonsNo(idx.getAndSet(idx.get() + 1));
							one.setLessonsId(qyClassesLessons.getId());
							one.setStartTime(sdf.parse(begin));
							one.setEndTime(sdf.parse(end));
							one.setAppointmentStatus("0");
						} catch (ParseException e) {
							throw new RuntimeException(e);
						} catch (InvocationTargetException e) {
							throw new RuntimeException(e);
						} catch (IllegalAccessException e) {
							throw new RuntimeException(e);
						}
						qyClassesLessonsDetailsService.save(one);
//						QyClassesLessonsDetailsEntity temp = qyClassesLessonsDetailsService.getOne(Condition.getQueryWrapper(one));
//						if(temp == null){
//							one.setAppointmentStatus("0");
//							qyClassesLessonsDetailsService.save(one);
//						}
					});
				}
				break;
				case 1://每天
				{
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					List<String> days = getDays(qyClassesLessons.getStartTime(), qyClassesLessons.getEndTime());
					qyClassesLessonsDetailsService.realReamove(map);
					AtomicReference<Integer> idx = new AtomicReference<>(1);
					days.forEach(item->{
						String begin = item+" "+qyClassesLessons.getSubStartTime()+":00";
						String end	 = item+" "+qyClassesLessons.getSubEndTime()+":00";

						QyClassesLessonsDetailsEntity one = new QyClassesLessonsDetailsEntity();

						try {
							BeanUtils.copyProperties(one,qyClassesLessons);
							one.setLessonsNo(idx.getAndSet(idx.get() + 1));
							one.setLessonsId(qyClassesLessons.getId());
							one.setStartTime(sdf.parse(begin));
							one.setEndTime(sdf.parse(end));
							one.setAppointmentStatus("0");
						} catch (ParseException e) {
							throw new RuntimeException(e);
						} catch (InvocationTargetException e) {
							throw new RuntimeException(e);
						} catch (IllegalAccessException e) {
							throw new RuntimeException(e);
						}
						qyClassesLessonsDetailsService.save(one);
//						QyClassesLessonsDetailsEntity temp = qyClassesLessonsDetailsService.getOne(Condition.getQueryWrapper(one));
//						if(temp == null){
//							one.setAppointmentStatus("0");
//							qyClassesLessonsDetailsService.save(one);
//						}
					});
				}
				break;
				case 2://每周 几
				{
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					List<String> days = getWeekDays(qyClassesLessons.getStartTime(), qyClassesLessons.getEndTime(),DayOfWeek.of( qyClassesLessons.getRate()));
					qyClassesLessonsDetailsService.realReamove(map);
					AtomicReference<Integer> idx = new AtomicReference<>(1);
					days.forEach(item->{
						String begin = item+" "+qyClassesLessons.getSubStartTime()+":00";
						String end	 = item+" "+qyClassesLessons.getSubEndTime()+":00";
						QyClassesLessonsDetailsEntity one = new QyClassesLessonsDetailsEntity();

						try {
							BeanUtils.copyProperties(one,qyClassesLessons);
							one.setLessonsNo(idx.getAndSet(idx.get() + 1));
							one.setLessonsId(qyClassesLessons.getId());
							one.setStartTime(sdf.parse(begin));
							one.setEndTime(sdf.parse(end));
						} catch (ParseException e) {
							throw new RuntimeException(e);
						} catch (InvocationTargetException e) {
							throw new RuntimeException(e);
						} catch (IllegalAccessException e) {
							throw new RuntimeException(e);
						}
						QyClassesLessonsDetailsEntity temp = qyClassesLessonsDetailsService.getOne(Condition.getQueryWrapper(one));
						if(temp == null){
							one.setAppointmentStatus("0");
							qyClassesLessonsDetailsService.save(one);
						}
					});
				}
				break;

			}
		}

		return R.status(tage);
	}

	/**
	 * 课表 修改
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@Operation(summary = "修改", description  = "传入qyClassesLessons")
	public R update(@Valid @RequestBody QyClassesLessonsEntity qyClassesLessons) {
		return R.status(qyClassesLessonsService.updateById(qyClassesLessons));
	}

	/**
	 * 课表 新增或修改
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@Operation(summary = "新增或修改", description  = "传入qyClassesLessons")
	public R submit(@Valid @RequestBody QyClassesLessonsEntity qyClassesLessons) {


		boolean tage = qyClassesLessonsService.saveOrUpdate(qyClassesLessons);
		Map<String, Object> map = new HashMap<>();
		map.put("lessons_id", qyClassesLessons.getId());
		if(tage){
			switch (Integer.valueOf( qyClassesLessons.getRepetitive())){
				case 0://不重复
				{
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					List<String> days = getDays(qyClassesLessons.getStartTime(), qyClassesLessons.getStartTime());
					qyClassesLessonsDetailsService.realReamove(map);
					AtomicReference<Integer> idx = new AtomicReference<>(1);
					days.forEach(item->{
						String begin = item+" "+qyClassesLessons.getSubStartTime()+":00";
						String end	 = item+" "+qyClassesLessons.getSubEndTime()+":00";

						QyClassesLessonsDetailsEntity one = new QyClassesLessonsDetailsEntity();

						try {
							BeanUtils.copyProperties(one,qyClassesLessons);
							one.setId(null);
							one.setLessonsNo(idx.getAndSet(idx.get() + 1));
							one.setLessonsId(qyClassesLessons.getId());
							one.setStartTime(sdf.parse(begin));
							one.setEndTime(sdf.parse(end));
							one.setAppointmentStatus("0");
						} catch (ParseException e) {
							throw new RuntimeException(e);
						} catch (InvocationTargetException e) {
							throw new RuntimeException(e);
						} catch (IllegalAccessException e) {
							throw new RuntimeException(e);
						}
						qyClassesLessonsDetailsService.save(one);
//						QyClassesLessonsDetailsEntity temp = qyClassesLessonsDetailsService.getOne(Condition.getQueryWrapper(one));
//						if(temp == null){
//							one.setAppointmentStatus("0");
//							qyClassesLessonsDetailsService.save(one);
//						}
					});
				}
				break;
				case 1://每天
				{
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					List<String> days = getDays(qyClassesLessons.getStartTime(), qyClassesLessons.getEndTime());
					qyClassesLessonsDetailsService.realReamove(map);
					AtomicReference<Integer> idx = new AtomicReference<>(1);
					days.forEach(item->{
						String begin = item+" "+qyClassesLessons.getSubStartTime()+":00";
						String end	 = item+" "+qyClassesLessons.getSubEndTime()+":00";

						QyClassesLessonsDetailsEntity one = new QyClassesLessonsDetailsEntity();

						try {
							BeanUtils.copyProperties(one,qyClassesLessons);
							one.setId(null);
							one.setLessonsNo(idx.getAndSet(idx.get() + 1));
							one.setLessonsId(qyClassesLessons.getId());
							one.setStartTime(sdf.parse(begin));
							one.setEndTime(sdf.parse(end));
							one.setAppointmentStatus("0");
						} catch (ParseException e) {
							throw new RuntimeException(e);
						} catch (InvocationTargetException e) {
							throw new RuntimeException(e);
						} catch (IllegalAccessException e) {
							throw new RuntimeException(e);
						}
						qyClassesLessonsDetailsService.save(one);
//						QyClassesLessonsDetailsEntity temp = qyClassesLessonsDetailsService.getOne(Condition.getQueryWrapper(one));
//						if(temp == null){
//							one.setAppointmentStatus("0");
//							qyClassesLessonsDetailsService.save(one);
//						}
					});
				}
				break;
				case 2://每周 几
				{
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					List<String> days = getWeekDays(qyClassesLessons.getStartTime(), qyClassesLessons.getEndTime(), DayOfWeek.of( qyClassesLessons.getRate()));
					qyClassesLessonsDetailsService.realReamove(map);
					AtomicReference<Integer> idx = new AtomicReference<>(1);
					days.forEach(item->{
						String begin = item+" "+qyClassesLessons.getSubStartTime()+":00";
						String end	 = item+" "+qyClassesLessons.getSubEndTime()+":00";
						QyClassesLessonsDetailsEntity one = new QyClassesLessonsDetailsEntity();

						try {
							BeanUtils.copyProperties(one,qyClassesLessons);
							one.setId(null);
							one.setLessonsNo(idx.getAndSet(idx.get() + 1));
							one.setLessonsId(qyClassesLessons.getId());
							one.setStartTime(sdf.parse(begin));
							one.setEndTime(sdf.parse(end));
						} catch (ParseException | IllegalAccessException | InvocationTargetException e) {
							throw new RuntimeException(e);
						}
						QyClassesLessonsDetailsEntity temp = qyClassesLessonsDetailsService.getOne(Condition.getQueryWrapper(one));
						if(temp == null){
							one.setAppointmentStatus("0");
							qyClassesLessonsDetailsService.save(one);
						}
					});
				}
				break;

			}
		}

		return R.status(tage);

//		return R.status(qyClassesLessonsService.saveOrUpdate(qyClassesLessons));
	}

	/**
	 * 课表 删除
	 */
	@PostMapping("/remove")
	@ApiOperationSupport(order = 7)
	@Operation(summary = "逻辑删除", description  = "传入ids")
	public R remove(@Parameter(name = "主键集合", required = true) @RequestParam String ids) {
		return R.status(qyClassesLessonsService.deleteLogic(Func.toLongList(ids)));
	}


	/**
	 * 导出数据
	 */
	@PreAuth(RoleConstant.HAS_ROLE_ADMIN)
	@GetMapping("/export-qyClassesLessons")
	@ApiOperationSupport(order = 9)
	@Operation(summary = "导出数据", description  = "传入qyClassesLessons")
	public void exportQyClassesLessons(@Parameter(hidden = true) @RequestParam Map<String, Object> qyClassesLessons, XrskUser XrskUser, HttpServletResponse response) {
		QueryWrapper<QyClassesLessonsEntity> queryWrapper = Condition.getQueryWrapper(qyClassesLessons, QyClassesLessonsEntity.class);
		//if (!AuthUtil.isAdministrator()) {
		//	queryWrapper.lambda().eq(QyClassesLessons::getTenantId, XrskUser.getTenantId());
		//}
		queryWrapper.lambda().eq(QyClassesLessonsEntity::getIsDeleted, XrskConstant.DB_NOT_DELETED);
		List<QyClassesLessonsExcel> list = qyClassesLessonsService.exportQyClassesLessons(queryWrapper);
		ExcelUtil.export(response, "课表数据" + DateUtil.time(), "课表数据表", list, QyClassesLessonsExcel.class);
	}

}
